<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Sale_Detail_Results_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('xlsimport/php-excel-reader/excel_reader2');
        $this->load->helper('xlsimport/spreadsheetreader.php');
        $this->load->model('saledetailresult', '', true);
        $this->load->model('user', '', true);

        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }

        //$this->LoggedUser = $this->user->getLoggedUser();
        
        $this->load->library('authentication');$this->load->helper('t');
        $this->loggedUser = $this->authentication->getLoggedUser();$this->authentication->redirectIfNotBe( array('HR', 'SC'));
    }

    function index_content($region = 'all', $title = 'all', $ss = 'all') {
        $this->load->helper('form');
        $this->load->model('evaluation', '', true);

        // load dropdown region, title, thực hiện filter
        //$titles = $this->user->get_enum_values();
        $titles = array('NR' => 'NR', 'PG' => 'PG', 'BS' => 'BS', 'Medical' => 'Medical');
        $viewData['titles'] = $titles;
        
        $this->load->model('region');
        $regions = $this->region->get_list();
        $viewData['regions'] = $regions;
                
        $regionDic = array();       
        foreach ($regions as $key => $value)
        {
           $regionDic[$value['rsm_code']]= $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;
        
        // danh sách SS
        $ssList = $this->user->get_list_by_title(array('SS', 'KAS'), array('status' => 'active'));
        $viewData['ssList'] = $ssList;
        
        $users = array();
        if($title != 'all')
        {
            $viewData['filterTitle'] = $title;
            switch ($title)
            {
                case 'NR':
                    $users = $this->user->get_list_by_title(array('NR', 'NRTL'), array('status' => 'active'));
                    break;
                case 'PG':
                    $users = $this->user->get_list_by_title(array('PG', 'PGTL'), array('status' => 'active'));
                    break;
                case 'BS':
                    $users = $this->user->get_list_by_title(array('BS', 'BSTL'), array('status' => 'active'));
                    break;
                case 'Medical':
                    $users = $this->user->get_list_by_title(array('MedNR', 'MedBS', 'MedTL'), array('status' => 'active'));
                    break;
            }
        }
        else
        {
            $users = $this->user->get_list_by_title(get_employee_titles(), array('status' => 'active'));
        }
        if($region != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if($eachUser['rsm_code'] == $region)
                {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterRegion'] = $region;
        }
        if ($ss != 'all') {
            $temp = array();
            foreach ($users as $eachUser) {
                if ($eachUser['supervisor_code'] == $ss) {
                    $temp[] = $eachUser;
                }
            }
            $users = $temp;
            $viewData['filterSS'] = $ss;
        }
        
        // đợt đánh giá mới nhất
        $evaluation = $this->evaluation->get_last();
        $viewData['evaluation'] = $evaluation;
        
        // truy vấn kết quả của từng user
//        $daCoSP= 0;
//        $chuaCoSP = 0;
        foreach ($users as &$eachUser) {
            $saleResult = $this->saledetailresult->get_first_where(array('user_code' => $eachUser['code'], 'eid' => $evaluation['id']));
            $eachUser['saleResult'] = $saleResult;
//            if($saleResult == false)
//            {
//                $chuaCoSP++;
//            }
//            else
//            {
//                $daCoSP++;
//            }
        }
        
        $viewData['rows'] = $users;
        $viewData['allUsers'] = count($users);
//        $viewData['chuaCoSP'] = $chuaCoSP;
//        $viewData['daCoSP'] = $daCoSP;
        
//        $chartData = array();
//        $chartData[] = array('Loại', 'Số lượng');
//        $chartData[] = array('Đã có Sales performance', $daCoSP);
//        $chartData[] = array('Chưa có Sales performance', $chuaCoSP);        
//        $viewData['chartData'] = json_encode($chartData);
        
        return $viewData;
    }

    function index($region = 'all', $title = 'all', $sp = 'all', $ss = 'all') {

        $viewData = $this->index_content($region, $title, $ss);
        $users = $viewData['rows'];
        
        // truy vấn kết quả của từng user
//        $daCoSP= 0;
//        $chuaCoSP = 0;
        foreach ($users as $eachUser) {
//            if($eachUser['saleResult'] == false)
//            {
//                $chuaCoSP++;
//            }
//            else
//            {
//                $daCoSP++;
//            }
            
            // filter đã có sp hay chưa
            if ($sp == 'done') {
                if ($eachUser['saleResult'] == false) {
                    unset($users[array_search($eachUser, $users)]);
                    continue;
                }
            } else if ($sp == 'not') {
                if ($eachUser['saleResult'] != false) {
                    unset($users[array_search($eachUser, $users)]);
                    continue;
                }
            }
        }
        $viewData['rows'] = $users;
        $viewData['filterSp'] = $sp;
        
//        $viewData['chuaCoSP'] = $chuaCoSP;
//        $viewData['daCoSP'] = $daCoSP;
        
//        
//        $chartData = array();
//        $chartData[] = array('Loại', 'Số lượng');
//        $chartData[] = array('Đã có Sales performance', $daCoSP);
//        $chartData[] = array('Chưa có Sales performance', $chuaCoSP);        
//        $viewData['chartData'] = json_encode($chartData);

        $this->load->view(get_folder($this->loggedUser->title).'/sale_detail_results_list', $viewData);
        
    }
    
    function report($region = 'all', $title = 'all', $sp = 'all', $ss = 'all') {

        $viewData = $this->index_content($region, $title, $ss);
        $users = $viewData['rows'];
        
        // truy vấn kết quả của từng user
        $daCoSP= 0;
        $chuaCoSP = 0;
        foreach ($users as $eachUser) {
            if($eachUser['saleResult'] == false)
            {
                $chuaCoSP++;
            }
            else
            {
                $daCoSP++;
            }
            
            // filter đã có sp hay chưa
            if ($sp == 'done') {
                if ($eachUser['saleResult'] == false) {
                    unset($users[array_search($eachUser, $users)]);
                    continue;
                }
            } else if ($sp == 'not') {
                if ($eachUser['saleResult'] != false) {
                    unset($users[array_search($eachUser, $users)]);
                    continue;
                }
            }
        }
        $viewData['rows'] = $users;
        $viewData['chuaCoSP'] = $chuaCoSP;
        $viewData['daCoSP'] = $daCoSP;
        $viewData['filterSp'] = $sp;
        
        $chartData = array();
        $chartData[] = array('Loại', 'Số lượng');
        $chartData[] = array('Đã có Sales performance', $daCoSP);
        $chartData[] = array('Chưa có Sales performance', $chuaCoSP);        
        $viewData['chartData'] = json_encode($chartData);
        

        $this->load->view(get_folder($this->loggedUser->title).'/sale_detail_results_report', $viewData);
        
    }
    
    function upload() {
//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
        if (isset($_FILES['xlsfile'])) {
            $targets = 'xls/';
            $targets = $targets . basename($_FILES['xlsfile']['name']);
            $docadd = ($_FILES['xlsfile']['name']);
            if (move_uploaded_file($_FILES['xlsfile']['tmp_name'], $targets)) {
                $Filepath = $targets;
                $allxlsdata = array();
                date_default_timezone_set('UTC');

                $StartMem = memory_get_usage();
                //echo '---------------------------------'.PHP_EOL;
                //echo 'Starting memory: '.$StartMem.PHP_EOL;
                //echo '---------------------------------'.PHP_EOL;

                try {
                    $Spreadsheet = new SpreadsheetReader($Filepath);
                    $BaseMem = memory_get_usage();

                    $Sheets = $Spreadsheet->Sheets();

                    //echo '---------------------------------'.PHP_EOL;
                    //echo 'Spreadsheets:'.PHP_EOL;
                    //print_r($Sheets);
                    //echo '---------------------------------'.PHP_EOL;
                    //echo '---------------------------------'.PHP_EOL;

                    foreach ($Sheets as $Index => $Name) {
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** Sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;

                        $Time = microtime(true);

                        $Spreadsheet->ChangeSheet($Index);
                        // Tâm
                        // chỉ lấy dữ liệu sheet đầu tiên. Nếu muốn lấy shiêu sheet và bỏ qua sheet trống -> count $Spreadsheet
                        if($Index > 0)
                        {
                            break;
                        }

                        foreach ($Spreadsheet as $Key => $Row) {
                            //echo $Key.': ';
                            if ($Row) {
                                //print_r($Row);
                                $allxlsdata[] = $Row;
                            } else {
                                var_dump($Row);
                            }
                            $CurrentMem = memory_get_usage();

                            //echo 'Memory: '.($CurrentMem - $BaseMem).' current, '.$CurrentMem.' base'.PHP_EOL;
                            //echo '---------------------------------'.PHP_EOL;

                            if ($Key && ($Key % 500 == 0)) {
                                //echo '---------------------------------'.PHP_EOL;
                                //echo 'Time: '.(microtime(true) - $Time);
                                //echo '---------------------------------'.PHP_EOL;
                            }
                        }

                        //	echo PHP_EOL.'---------------------------------'.PHP_EOL;
                        //echo 'Time: '.(microtime(true) - $Time);
                        //echo PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** End of sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                    }
                } catch (Exception $E) {
                    echo $E->getMessage();
                }
                
                $this->load->model('evaluation', '', true);
                $evaluation = $this->evaluation->get_last();


                $this->saledetailresult->import($allxlsdata, $evaluation['id']);
            }
        } else {
            echo "Error: " . $_FILES["file"]["error"];
        }
        redirect(get_folder($this->loggedUser->title).'/sale_detail_results');
    }
    
    
    
    
    function addedit() {
        show_404();
    }
    
    

}
?>













